<?php
/**
 * Created by Administrator
 * User: longli
 * Date: 2020/08/21
 * Time: 19:27
 * @link http://www.lmterp.cn
 */

namespace app\common\service\export;

use app\common\library\Tools;
use app\common\model\Account;
use app\common\model\AccountPlatform;
use app\common\model\ProductPlatformSku;

/**
 * 导出内部sku和平台sku的映射关系
 * Class PlatformSku
 * @package app\common\service\export
 */
class PlatformSku extends BaseExport
{
    protected $prefix = "platform-sku";

    public function getHeader()
    {
        return [
            "sku.platform_sku" => '平台SKU',
            "sku.sku" => '内部SKU',
            "account.username" => '销售账号',
            "platform.name" => '销售平台',
            "sku.create_time" => '生成时间',
        ];
    }

    public function getData($condition = [])
    {
        $pWhere = $this->parseWhere($condition);
        $sku = $pWhere['sku'];
        $account = $pWhere['account'];
        $platform = $pWhere['platform'];
        // 获取需要导出的字段
        $tempField = $this->getField();
        $skuModel = ProductPlatformSku::with(["account.platform"])->where($sku);
        if(!empty($account))
        {
            $skuModel->where("account_id", "in", function($query)use($account)
            {
                $query->table(Account::getTable())
                    ->field("account_id")
                    ->where($account);
            });
        }
        if(!empty($platform))
        {
            $skuModel->where("account_id", "in", function($query)use($platform)
            {
                $query->table(Account::getTable() . " a")
                    ->field("a.account_id")
                    ->join(AccountPlatform::getTable() . " p", "a.platform_id=p.platform_id")
                    ->where($platform);
            });
        }

        $ret = [];
        foreach($skuModel->select() as $k => $item)
        {
            $ret[$k] = [];
            $ret[$k] += Tools::replaceArrayKey($tempField['sku'], array_intersect_key($item->toArray(), $tempField['sku']));
            $ret[$k] += Tools::replaceArrayKey($tempField['account'], array_intersect_key($item->account->toArray(), $tempField['account']));
            $ret[$k] += Tools::replaceArrayKey($tempField['platform'], array_intersect_key($item->account->platform->toArray(), $tempField['platform']));
        }
        $this->sortData($ret);
        return $ret;
    }
}